﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;

namespace Mimoza.PluginLayer
{
    class ExecutePluginLoader
    {
        public ExecutePluginLoader(string path, string pluginIdentity)
        {
            int dotPos = pluginIdentity.IndexOf('.');
            if (dotPos < 0)
            {
                Common.Logger.Log.Error(
                    "ExecutePluginLoader wrong identity of plugin {0}",
                    pluginIdentity);
                return;
            }

            string assemblyName = path + "/" + pluginIdentity.Substring(0,dotPos) + ".dll";
            string typeName = pluginIdentity.Substring(dotPos + 1);

            Common.Logger.Log.Trace(
                    "ExecutePluginLoader load plugin: assembly - {0}, type - {1}",
                    assemblyName, typeName);
            try
            {
                Assembly assembly = Assembly.LoadFrom(assemblyName);
                if (assembly == null)
                {
                    Common.Logger.Log.Error(
                        "ExecutePluginLoader can't load assembly {0}",
                        assemblyName);
                    return;
                }

                IExecutePlugin plugin = (IExecutePlugin)assembly.CreateInstance(typeName);
                if (plugin == null)
                {
                    Common.Logger.Log.Error("ExecutePluginLoader can't create plugin {0}",
                        typeName);
                }

                m_plugin = plugin;
            }
            catch (System.Exception e)
            {
                Common.Logger.Log.Error("Error in initializing plugin fileName - '" +
                    assemblyName + "' Error - " + e.ToString());
            }
        }

        public IExecutePlugin Plugin
        {
            get { return m_plugin; }
        }

        IExecutePlugin m_plugin = null;
    }
}
